<template>
  <div class="page">
    <h2>药品目录维护</h2>

    <div class="controls">
      <el-input v-model="q" placeholder="按名称或编码搜索" clearable style="flex:1" @clear="onClear" />

      <el-select v-model="filterCategory" placeholder="全部类别" style="width:180px">
        <el-option label="全部类别" :value="''" />
        <el-option v-for="c in categories" :key="c" :label="c" :value="c" />
      </el-select>

      <el-select v-model="filterStatus" placeholder="全部状态" style="width:140px">
        <el-option label="全部状态" :value="''" />
        <el-option label="启用" value="active" />
        <el-option label="停用" value="inactive" />
      </el-select>

      <div style="display:flex;gap:8px">
        <el-button type="primary" @click="openModal()">新增药品</el-button>
        <el-button @click="() => fileInput.click()">导入CSV</el-button>
        <el-button @click="exportCSV">导出CSV</el-button>
      </div>
    </div>

    
    <el-table :data="filtered" stripe border style="width:100%;margin-top:12px" @selection-change="onSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="code" label="编码" width="120" />
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="category" label="类别" width="140" />
      <el-table-column prop="dosage" label="剂型/规格" width="160" />
      <el-table-column prop="manufacturer" label="厂家" width="160" />
      <el-table-column prop="price" label="单价" width="100">
        <template #default="{ row }">¥{{ (row.price||0).toFixed(2) }}</template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status==='active' ? 'success' : 'info'">{{ row.status==='active' ? '启用' : '停用' }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="190">
        <template #default="{ row }">
          <el-button size="small" @click="openModal(row.id)">编辑</el-button>
          <el-button size="small" @click="toggleStatus(row.id)" style="margin-left:8px">{{ row.status==='active' ? '停用' : '启用' }}</el-button>
          <el-button size="small" type="danger" @click="deleteOne(row.id)" style="margin-left:8px">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top:8px;display:flex;gap:8px;align-items:center">
      <el-button @click="batchSetStatus('inactive')">批量停用</el-button>
      <el-button @click="batchSetStatus('active')">批量启用</el-button>
      <el-button type="danger" @click="batchDelete">批量删除</el-button>
      <div style="flex:1"></div>
      <div class="muted">已选：{{ selectedIds.length }} 项</div>
    </div>

    <!-- dialog -->
    <el-dialog :title="editingId ? '编辑药品' : '新增药品'" v-model="showModal" width="520px">
      <el-form :model="form" label-width="100px">
        <el-form-item label="编码">
          <el-input v-model="form.code" />
        </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="类别">
          <el-input v-model="form.category" placeholder="例如：处方药/中成药/耗材" />
        </el-form-item>
        <el-form-item label="剂型/规格">
          <el-input v-model="form.dosage" />
        </el-form-item>
        <el-form-item label="厂家">
          <el-input v-model="form.manufacturer" />
        </el-form-item>
        <el-form-item label="单价">
          <el-input-number v-model="form.price" :step="0.01" :min="0" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status" style="width:160px">
            <el-option label="启用" value="active" />
            <el-option label="停用" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item label="说明">
          <el-input v-model="form.desc" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeModal">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </template>
    </el-dialog>

    <input ref="fileInput" type="file" accept=".csv" style="display:none" @change="handleFile" />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const DEFAULT_DATA = [
  {id:1,code:'D0001',name:'阿莫西林胶囊',category:'处方药',dosage:'0.5g*24粒',manufacturer:'某药业',price:12.5,status:'active',desc:'抗菌药'},
  {id:2,code:'D0002',name:'头孢克肟片',category:'处方药',dosage:'0.1g*10片',manufacturer:'示例制药',price:8.0,status:'active',desc:'广谱头孢'},
  {id:3,code:'D0101',name:'维生素C片',category:'OTC',dosage:'0.1g*60片',manufacturer:'维生素厂',price:5.2,status:'inactive',desc:'补充营养'},
  {id:4,code:'D0003',name:'布洛芬片',category:'OTC',dosage:'0.2g*20片',manufacturer:'安康制药',price:6.5,status:'active',desc:'解热镇痛'},
  {id:5,code:'D0004',name:'阿司匹林片',category:'OTC',dosage:'0.1g*100片',manufacturer:'百草堂',price:10.0,status:'active',desc:'抗血小板聚集'},
  {id:6,code:'D0005',name:'银杏叶片',category:'中成药',dosage:'0.05g*30片',manufacturer:'国药集团',price:18.0,status:'inactive',desc:'活血化瘀'},
  {id:7,code:'D0006',name:'感冒灵颗粒',category:'处方药',dosage:'10g*10袋',manufacturer:'华润制药',price:9.9,status:'active',desc:'解表止咳'},
  {id:8,code:'D0007',name:'消毒棉片',category:'耗材',dosage:'50片/盒',manufacturer:'医疗器械厂',price:4.5,status:'active',desc:'一次性消毒'},
  {id:9,code:'D0008',name:'胰岛素注射液',category:'处方药',dosage:'100IU/ml',manufacturer:'某生物',price:120.0,status:'active',desc:'血糖控制'},
  {id:10,code:'D0009',name:'氯雷他定片',category:'OTC',dosage:'10mg*14片',manufacturer:'康泰药业',price:7.5,status:'inactive',desc:'抗过敏'}
];

const data = ref([]);

// 新增：缺失的响应式变量，避免 ReferenceError
const q = ref('');
const filterCategory = ref('');
const filterStatus = ref('');
const selectedRows = ref([]);
const selectedIds = ref([]);
const showModal = ref(false);
const editingId = ref(null);
const form = reactive({ code:'', name:'', category:'', dosage:'', manufacturer:'', price:0, status:'active', desc:'' });
const fileInput = ref(null);

onMounted(()=>{
  load();
});

function load(){
  // 直接加载内置数据，不使用 localStorage
  data.value = JSON.parse(JSON.stringify(DEFAULT_DATA));
}
function saveData(){ /* 不再使用 localStorage，保持函数占位以兼容其他逻辑 */ }

const categories = computed(()=>{ const s = new Set(data.value.map(i=>i.category).filter(Boolean)); return Array.from(s); });

const filtered = computed(()=>{
  const qq = q.value.trim().toLowerCase();
  return data.value.filter(d=>{
    if(qq && !(d.name.toLowerCase().includes(qq) || d.code.toLowerCase().includes(qq))) return false;
    if(filterCategory.value && d.category !== filterCategory.value) return false;
    if(filterStatus.value && d.status !== filterStatus.value) return false;
    return true;
  });
});

watch(selectedRows, v=>{ selectedIds.value = v.map(i=>i.id); });

function onSelectionChange(rows){ selectedRows.value = rows; }

function openModal(id){
  editingId.value = id || null;
  if(id){ const it = data.value.find(x=>x.id===id); if(it){ Object.assign(form, JSON.parse(JSON.stringify(it))); } }
  else{ Object.assign(form,{code:'',name:'',category:'',dosage:'',manufacturer:'',price:0,status:'active',desc:''}); }
  showModal.value = true;
}
function closeModal(){ showModal.value = false; editingId.value = null; }
function save(){ if(!form.code || !form.name){ ElMessage.warning('编码和名称为必填项'); return; }
  if(editingId.value){ const it = data.value.find(x=>x.id===editingId.value); if(it) Object.assign(it, JSON.parse(JSON.stringify(form))); }
  else{ const nid = (data.value.reduce((s,i)=>Math.max(s,i.id),0) || 0) + 1; data.value.push(Object.assign({id:nid}, JSON.parse(JSON.stringify(form)))); }
  saveData(); showModal.value=false; }

function deleteOne(id){ ElMessageBox.confirm('确认删除该药品？','删除确认',{ confirmButtonText:'确定', cancelButtonText:'取消', type:'warning' })
  .then(()=>{ data.value = data.value.filter(x=>x.id!==id); saveData(); ElMessage.success('已删除'); })
  .catch(()=>{});
}
function toggleStatus(id){ const it = data.value.find(x=>x.id===id); if(!it) return; it.status = it.status==='active'?'inactive':'active'; saveData(); }

function getSelectedIds(){ return selectedIds.value.slice(); }
function batchSetStatus(s){ const ids = getSelectedIds(); if(ids.length===0){ ElMessage.warning('请选择至少一项'); return; } data.value.forEach(d=>{ if(ids.includes(d.id)) d.status = s; }); saveData(); ElMessage.success('操作完成'); }
function batchDelete(){ const ids = getSelectedIds(); if(ids.length===0){ ElMessage.warning('请选择至少一项'); return; } ElMessageBox.confirm(`确认删除 ${ids.length} 条记录？`,'批量删除',{ confirmButtonText:'确定', cancelButtonText:'取消', type:'warning' })
  .then(()=>{ data.value = data.value.filter(d=>!ids.includes(d.id)); saveData(); selectedIds.value = []; selectedRows.value = []; ElMessage.success('已删除'); })
  .catch(()=>{});
}

function exportCSV(){
  const csv = [ ['id','code','name','category','dosage','manufacturer','price','status','desc'], ...data.value.map(d=>[d.id,d.code,d.name,d.category,d.dosage||'',d.manufacturer||'',d.price,d.status,d.desc||'']) ];
  const csvContent = csv.map(r=>r.map(cell=>`"${String(cell).replace(/"/g,'""')}"`).join(',')).join('\n');
  const blob = new Blob([csvContent],{type:'text/csv;charset=utf-8;'});
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a'); a.href=url; a.download='drug_catalog.csv'; document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url);
}

function handleFile(e){ const f = e.target.files[0]; if(!f) return; const reader = new FileReader(); reader.onload = function(ev){ try{
  const text = ev.target.result;
  const rows = text.split(/\r?\n/).map(r=>r.trim()).filter(Boolean);
  if(rows.length<2){ ElMessage.warning('没有有效数据'); return; }
  const headers = parseCSVLine(rows[0]);
  const items = rows.slice(1).map(r=>parseCSVLine(r)).map(cols=>{ const obj={}; headers.forEach((h,i)=>obj[h.trim()]=cols[i]||''); return obj; });
  items.forEach(it=>{
    const id = it.id?parseInt(it.id):null;
    if(id){ const ex = data.value.find(x=>x.id===id); if(ex){ ex.code = it.code||ex.code; ex.name = it.name||ex.name; ex.category = it.category||ex.category; ex.dosage = it.dosage||ex.dosage; ex.manufacturer = it.manufacturer||ex.manufacturer; ex.price = parseFloat(it.price)||ex.price; ex.status = it.status||ex.status; ex.desc = it.desc||ex.desc; return; } }
    const nid = (data.value.reduce((s,i)=>Math.max(s,i.id),0) || 0) + 1;
    data.value.push({id:nid,code:it.code||('C'+nid),name:it.name||'未命名',category:it.category||'',dosage:it.dosage||'',manufacturer:it.manufacturer||'',price:parseFloat(it.price)||0,status:it.status||'active',desc:it.desc||''});
  });
  saveData(); ElMessage.success('导入完成');
 }catch(err){ ElMessage.error('导入失败'); }}; reader.readAsText(f,'utf-8'); e.target.value=''; }

function parseCSVLine(line){ const cols=[]; let cur=''; let inQ=false; for(let i=0;i<line.length;i++){ const ch=line[i]; if(inQ){ if(ch==='"'){ if(line[i+1]==='"'){ cur+='"'; i++; }else{ inQ=false; } }else{ cur+=ch; } }else{ if(ch==='"'){ inQ=true; }else if(ch===','){ cols.push(cur); cur=''; }else{ cur+=ch; } } } cols.push(cur); return cols; }

function onClear(){ /* search cleared */ }
</script>

<style scoped>
.page{font-family: Arial, "Microsoft YaHei", sans-serif; margin:10px;}
h2{margin-top:-10px}
.controls{display:flex;gap:8px;margin-bottom:12px;align-items:center}
.muted{color:#666;font-size:13px}
</style>